// permission.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import {
  Equal,
  EqualOperator,
  FindOneOptions,
  FindOptionsWhere,
  getManager,
  Repository,
} from 'typeorm';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';
import { Permission } from './entities/permission.entity';
import { QueryPermissionDto } from './dto/query-permission.dto';

/**
 * 生成树形结构
 * @param permissions
 */
// function generatePermissions(permissions) {
//   const parentPermissions = permissions.filter((perm) => {
//     if (perm.parentId === '') {
//       return perm;
//     }
//   });
//   const map = parentPermissions.map((parent) => {
//     parent.children = permissions.filter((child) => {
//       return child.parentId.toString() === parent.id.toString();
//     });
//     return parent;
//   });
//   return map;
// }

@Injectable()
export class PermissionService {
  constructor(
    @InjectRepository(Permission)
    private permission: Repository<Permission>,
  ) {}

  /**
   * 创建权限
   * 先判断是否有相同名称的权限，如果有，则提示已存在，如果没有，则创建
   * @param createPermissionDto
   */
  async create(createPermissionDto: CreatePermissionDto) {
    // 查询数据库，检查是否存在相同名称或代码的权限
    const findPermission = await this.permission
      .createQueryBuilder('permission')
      .where('permission.permName = :permName', {
        permName: createPermissionDto.permName,
      })
      .orWhere('permission.permCode = :permCode', {
        permCode: createPermissionDto.permCode,
      })
      .getOne();
    if (findPermission) {
      return {
        msg: `Permission "${createPermissionDto.permName}" already exists`,
      };
    }
    let parent = null;
    if (createPermissionDto.parentId) {
      parent = await this.permission.findOne({
        where: {
          id: createPermissionDto.parentId,
        },
      });
    }
    const entity = { ...createPermissionDto, parent };
    console.log(entity, 'entity');
    await this.permission.save(entity);
    return {
      msg: `Permission "${createPermissionDto.permName}" has been created successfully`,
    };
  }

  /**
   * 查询当前id的权限及其子权限
   * @param query
   */
  async findAll(query: QueryPermissionDto) {
    const treeRepository =
      this.permission.manager.getTreeRepository(Permission);
    let permTrees = null as Permission | Permission[];
    if (query.id) {
      const current = await this.permission.findOne({
        where: {
          id: query.id,
        },
      });
      if (!current) {
        return {
          msg: `Permission with ID "${query.id}" not found`,
        };
      }
      permTrees = await treeRepository.findDescendantsTree(current, {
        depth: 2,
      });
    } else {
      permTrees = await treeRepository.findTrees({ depth: 2 });
      console.log(permTrees[0].children, 'permTrees');
    }
    return {
      data: {
        permList: permTrees,
      },
    };
  }

  async findOne(id: string) {
    const treeRepository =
      this.permission.manager.getTreeRepository(Permission);
    const parent = await this.permission.findOne({ where: { id } });
    if (!parent) {
      return {
        msg: `Permission with ID "${id}" not found`,
      };
    }
    const permTrees = await treeRepository.findDescendantsTree(parent);
    return {
      data: permTrees,
    };
  }

  async update(id: string, updatePermissionDto: UpdatePermissionDto) {
    const permission = await this.permission.findOne({
      where: { id },
      relations: ['parent'],
    });

    if (!permission) {
      throw new Error(`Permission with ID "${id}" not found`);
    }

    /**
     * 更新父权限
     */
    if (updatePermissionDto.parentId) {
      const newParent = await this.permission.findOne({
        where: { id: updatePermissionDto.parentId },
      });

      if (!newParent) {
        throw new Error(
          `Parent permission with ID "${updatePermissionDto.parentId}" not found`,
        );
      }

      permission.parent = newParent;
    } else {
      permission.parent = null;
    }

    // 更新其他字段
    if (updatePermissionDto.permName) {
      permission.permName = updatePermissionDto.permName;
    }
    if (updatePermissionDto.permCode) {
      permission.permCode = updatePermissionDto.permCode;
    }

    await this.permission.save(permission);

    return {
      msg: `Permission with ID "${id}" has been updated successfully`,
    };
  }

  async remove(id: string) {
    const permission = await this.permission.findOne({
      where: { id },
    });
    if (!permission) {
      return {
        msg: `Permission with ID "${id}" not found,Can not remove`,
      };
    }
    await this.permission.remove(permission);
    return {
      msg: `Permission with ID "${id}" has been deleted successfully`,
    };
  }
}
